#pragma once
#include "Common.h"
#include "ThreadPool.h"

class TcpServer
{
private:
    int sock_;
    uint16_t port_;
    ThreadPool<Task>* tp_ptr;
public:
    TcpServer(uint16_t port):sock_(-1),port_(port),tp_ptr(new ThreadPool<Task>()){}
    void Init()
    {
        sock_ = socket(AF_INET,SOCK_STREAM,0);
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = INADDR_ANY;

        bind(sock_,(struct sockaddr*)&local,sizeof(local));
        listen(sock_,5);
    }
    void Start()
    {
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int accept_sock = accept(sock_,(struct sockaddr*)&peer,&len);
            if(accept_sock < 0)
                continue;
            Task t(accept_sock,std::string(inet_ntoa(peer.sin_addr)),ntohs(peer.sin_port));
            tp_ptr->Push(t);
        }
    }
};